const fs = require("fs");
const path = require("path");
const config = JSON.parse(fs.readFileSync(path.join(__dirname, "../..", "config.json"), "utf8"));
const { generateASSStyles } = require("./assStyles");
const { WhisperTranscriber } = require("./whisperTranscriber");

/**
 * 本地字幕转换器 - 基于Whisper
 */
class LocalSubtitleConverter {
  constructor() {
    // ASS字幕格式头部
    this.assHeader = "";
  }

  generateAssHeader() {
    const textStyles = config.projectSettings?.textStyles || {};
    return `[Script Info]
  Title: Default Aegisub file
  ScriptType: v4.00+
  WrapStyle: 0
  ScaledBorderAndShadow: yes
  YCbCr Matrix: TV.601
  PlayResX: ${config.projectSettings.videoWidth}
  PlayResY: ${config.projectSettings.videoHeight}
  
  [V4+ Styles]
  ${generateASSStyles(textStyles)}
  [Events]
  Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
  
`;
  }

  /**
   * 使用Whisper从视频中提取文本
   * @param {string} videoPath 视频文件路径
   * @returns {Promise<Object>} 转录结果对象
   */
  async extractTextWithWhisper(videoPath) {
    try {
      console.log("正在使用Whisper提取文本...");
      const transcription = await WhisperTranscriber.transcribe(videoPath, {
        model: 'base',
        language: 'en', // 根据需要调整语言
        output_format: 'srt'
      });
      
      console.log("Whisper转录完成");
      return transcription;
    } catch (error) {
      console.error("Whisper转录失败:", error);
      throw error;
    }
  }

  /**
   * 生成ASS字幕文件 (使用Whisper转录)
   * @param {string} videoPath 视频文件路径
   * @param {string} outputPath 输出ASS文件路径
   */
  async generateASSWithWhisper(videoPath, outputPath) {
    try {
      // 步骤1: 使用Whisper转录文本
      console.log("正在使用Whisper转录文本...");
      const whisperResult = await this.extractTextWithWhisper(videoPath);
      console.log("Whisper转录结果:", whisperResult);
      console.log("Whisper转录结果,srt:", whisperResult.srt);
      console.log("正在将SRT转换为ASS...");
      // 步骤2: 将SRT转换为ASS
      console.log("正在生成ASS字幕...");
      if (this.assHeader.length === 0) this.assHeader = this.generateAssHeader();
      
      const assContent = WhisperTranscriber.srtToAss(whisperResult.srt, this.assHeader);

      // 写入文件
      fs.writeFileSync(outputPath, assContent, "utf8");
      console.log(`  ASS字幕已生成: ${outputPath}`);

      return outputPath;
    } catch (error) {
      console.error("  生成字幕失败:", error);
      throw error;
    }
  }
}

// 导出类
module.exports = { LocalSubtitleConverter };
/*
async function main() {
  // 配置参数 - 请修改为实际路径
  const videoPath = 'input/mp3/kCtDawsZ.mp4';
  const outputPath = './local_subtitles.ass';

  try {
    // 创建转换器实例并生成字幕
    const converter = new LocalSubtitleConverter();
    
    // 使用Whisper生成ASS字幕
    await converter.generateASSWithWhisper(videoPath, outputPath);
    
    console.log('字幕生成完成!');
  } catch (error) {
    console.error('处理失败:', error);
  }
}

// 运行主函数
main();
*/